#pragma once
#include "x51AppMgr.h"
#include "x51_socket_info_mgr.h"
#include "detour_hook_function_ctrl.h"
#include "x51_prototol/protocol_mgr.h"
#include "system_api_def.h"
#include "x51_prototol/net_protocol_def.h"

static int WSAAPI HookWsaRecv(SOCKET s,
	LPWSABUF lpBuffers,
	DWORD dwBufferCount,
	LPDWORD lpNumberOfBytesRecvd,
	LPDWORD lpFlags,
	LPWSAOVERLAPPED lpOverlapped,
	LPWSAOVERLAPPED_COMPLETION_ROUTINE lpCompletionRoutine)
{
	const int MAX_BUFF_LEN = 65535;
	int len = 0;
	char buf[MAX_BUFF_LEN] = { 0 };
	for (DWORD i = 0; i < dwBufferCount; i++)
	{
		LPWSABUF lpBuffer = lpBuffers + i;
		if (len + lpBuffer->len < MAX_BUFF_LEN)
		{
			memcpy(buf + len, lpBuffer->buf, lpBuffer->len);
			len += lpBuffer->len;
		}
	}

	CX51SocketInfoMgr* scoket_mgr = CX51AppMgr::GetInstance()->GetSocketInfoMgr();
	assert(scoket_mgr);
	scoket_mgr->SaveSocketInfo(s);

	int res = 0;
	CDetourHookFunctionCtrl* func_ctrl = CX51AppMgr::GetInstance()->GetHookFunCtrl();
	assert(func_ctrl);
	WSARECVPROC system_recv = (WSARECVPROC)(func_ctrl->GetSystemFunc("WSARecv"));
	if (NULL == system_recv)
	{
		return res;
	}

	CProtocolMgr* protocol_mgr = CX51AppMgr::GetInstance()->GetProtocolMgr();
	assert(protocol_mgr);

	int handle_res = protocol_mgr->HandleRecvNetBuff(s, (char*)buf, len);
	if (handle_res == NHR_Continue)
	{
		return system_recv(s, lpBuffers, dwBufferCount, lpNumberOfBytesRecvd, lpFlags, lpOverlapped, lpCompletionRoutine);
	}
	else if (handle_res == NHR_Abandon)
	{
		return 0;
	}

	return 0;
}
